package cryptoutil


import (
	"crypto/sha256"
	"errors"
	"github.com/hyperledger/fabric/bccsp"
	"golang.org/x/crypto/sha3"
	"hash"
)

type Hasher interface {
	Hash(msg []byte) []byte
	GetHash() hash.Hash
}

type hasher struct {
	hash func() hash.Hash
}

func (h hasher) Hash(msg []byte) []byte {
	hasher := h.GetHash()
	hasher.Write(msg)
	return hasher.Sum(nil)
}

func (h hasher) GetHash() hash.Hash {
	return h.hash()
}

func Hash(msg []byte, opt bccsp.HashOpts) ([]byte, error) {
	var hasher hash.Hash
	switch opt.Algorithm() {
	case bccsp.SHA256:
		hasher = sha256.New()
	case bccsp.SHA3_256:
		hasher = sha3.New256()
	default:
		return nil, errors.New("not support hash func")
	}
	hasher.Write(msg)
	return hasher.Sum(nil), nil
}
